<template>
  <section class="todoapp">
    <TodoHeader @add="handleAdd" />
    <TodoMain
      :list="list2"
      @del="handleDel"
      @changeState="handleState"
      @changeAllState="changeAllState"
    />
    <TodoFooter
      :list="list"
      :flag="flag"
      @changeFlag="
        val => {
          flag = val
        }
      "
      @delCompleted="clearCompleted"
    />
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from '@/components/TodoMain.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  data () {
    return {
      list: JSON.parse(localStorage.getItem('todo-list')) || [],
      flag: 1 // 1--全部任务  2--进行中 3--已完成
    }
  },
  methods: {
    handleDel (id) {
      // console.log(id)
      this.list = this.list.filter(item => item.id !== id)
    },
    handleAdd (todoname) {
      // this.list.push()
      this.list.unshift({ id: Date.now(), name: todoname, isDone: false })
    },
    handleState (id) {
      const row = this.list.find(item => item.id === id)
      // row = { id: 14, name: '听歌', isDone: true }
      row.isDone = !row.isDone
    },
    clearCompleted () {
      this.list = this.list.filter(item => item.isDone === false)
    },
    changeAllState (val) {
      this.list.forEach(item => {
        item.isDone = val
      })
    }
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  computed: {
    list2 () {
      if (this.flag === 1) {
        return this.list
      } else if (this.flag === 2) {
        return this.list.filter(item => item.isDone === false)
      } else {
        return this.list.filter(item => item.isDone === true)
      }
    }
  },
  watch: {
    // list (变化后的值, 变化前的值) {}
    list: {
      handler (val) {
        localStorage.setItem('todo-list', JSON.stringify(val))
      },
      // immediate: true,
      deep: true // 因为涉及到对象属性isDone的修改，为了侦听到它的变化，必须加deep
    }
  }
}
</script>

<style></style>
